﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Budget
{
    public partial class Add_Purchase : Form
    {
        public Dictionary<int, string> CatIndexValueDict;
        delegate void InsertDelegate(string _date, string _cat, string _amount, string _desc, string _acct, string _company, string _location);
        private int TransctionID = -1;
        private Money.TransactionType TransType;
        public Add_Purchase()
        {
            InitializeComponent();
            InitializeForm();
        }

        public Add_Purchase(int _id, Money.TransactionType _transactionType)
        {
            InitializeComponent();
            InitializeForm();
            rbExpense.Visible = false;
            rbIncome.Visible = false;
            TransctionID = _id;
            TransType = _transactionType;
            DataTable dt = DatabaseQuery.ExecStringProc(StoredProcs.getTransactionFromID(_transactionType, _id));
            txtAmount.Text = dt.Rows[0]["Amount"].ToString();
            txtDesc.Text = dt.Rows[0]["Description"].ToString();
            txtCompany.Text = dt.Rows[0]["Company"].ToString();
            txtLocation.Text = dt.Rows[0]["Location"].ToString();
            dateTimePicker1.Value = Convert.ToDateTime(dt.Rows[0]["Date"].ToString());
            int key = Convert.ToInt32(dt.Rows[0]["Category"].ToString());
            string value = dbData.dictExpenseCategories[key];
            KeyValuePair<int, string> kvp = new KeyValuePair<int,string>(key,value);
            ddlCategory.SelectedItem = kvp;
        }
        public void InitializeForm()
        {
            txtLocation.Text = Properties.Settings.Default.DefaultLocation;

            DataTable dt = DatabaseQuery.ExecStringProc(StoredProcs.getColumnAutoComplete("Description",txtDesc.Text.Split(' ')));
            txtDesc.AutoCompleteCustomSource.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                txtDesc.AutoCompleteCustomSource.Add((string)dr[0]);
            }

            dt = DatabaseQuery.ExecStringProc(StoredProcs.getColumnAutoComplete("Location", txtDesc.Text.Split(' ')));
            txtLocation.AutoCompleteCustomSource.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                txtLocation.AutoCompleteCustomSource.Add((string)dr[0]);
            }

            dt = DatabaseQuery.ExecStringProc(StoredProcs.getColumnAutoComplete("Company", txtDesc.Text.Split(' ')));
            txtCompany.AutoCompleteCustomSource.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                txtCompany.AutoCompleteCustomSource.Add((string)dr[0]);
            }

            button1.Visible = false;
            ReloadCategoryDDL();
            lblStatus.Text = "";
        }
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            KeyValuePair<int, string> kvp = (KeyValuePair<int, string>)ddlCategory.SelectedItem;
            string cat = kvp.Key.ToString();
            if (TransctionID > -1)
            {
                try
                {
                    DatabaseQuery.ExecStringProcNoReturn(
                        StoredProcs.UpdateTransaction(TransType,
                                                      TransctionID,
                                                      txtCompany.Text,
                                                      txtLocation.Text,
                                                      txtAmount.Text,
                                                      dateTimePicker1.Value,
                                                      txtDesc.Text,
                                                      cat)
                                                );
                    lblStatus.Text = "Transaction Updated";
                    return;
                }
                catch
                {
                    lblStatus.Text = "ERROR Update Failed";
                }
            }

            //determine what method to call for update, set delegate
            InsertDelegate InsertFunc;
            if (rbExpense.Checked)
            {
                InsertFunc = new InsertDelegate(InsertExpense);
            }
            else
            {
                InsertFunc = new InsertDelegate(InsertIncome);
            }
            try
            {
                int inserts = 0;
                string date = dateTimePicker1.Value.ToString("MM/dd/yyyy");
                //KeyValuePair<int, string> kvp = (KeyValuePair<int, string>)ddlCategory.SelectedItem;
                //string cat = kvp.Key.ToString();
                string amount = txtAmount.Text.Replace("$","");
                amount = amount.Replace(",", "");
                string desc = txtDesc.Text;
                string acct = "";
                string company = txtCompany.Text;
                string location = txtLocation.Text;
                
                switch (ddlFrequency.SelectedItem.ToString())
                {
                    case "One Time":
                        InsertFunc(date, cat, amount, desc, acct,company,location);
                        break;
                    case "Monthly":
                        amount = (Convert.ToDecimal(amount) / Dates.getWeeksInMonth(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year)).ToString();
                        inserts = Dates.getWeeksInMonth(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year);
                        for (int i = 0; i < inserts; i++)
                        {
                            date = Dates.getFridaysInMonthList(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year)[i].ToString("MM/dd/yyyy");
                            InsertFunc(date, cat, amount, desc, acct,company,location);
                        }
                        break;
                    case "Bi-Weekly":
                        amount = (Convert.ToDecimal(amount) / 2).ToString();
                        inserts = 2;
                        DateTime tmpdate = dateTimePicker1.Value;
                        for (int i = 0; i < inserts; i++)
                        {
                            date = (tmpdate.ToString("MM/dd/yyyy"));
                            InsertFunc(date, cat, amount, desc, acct,company,location);
                            tmpdate = tmpdate.AddDays(-7);
                        }
                        break;
                }
                lblStatus.Text = String.Format("Added {0} {1} of {2}", 
                    cat,
                    rbExpense.Checked ? "Expense":"Income",
                    txtAmount.Text);
                txtAmount.Text = "";
            }
            catch
            {
                lblStatus.Text = "Error Occured Somewhere!";
            }
        }
        public void InsertExpense(string _date, string _cat, string _amount, string _desc, string _acct, string _company, string _location)
        {
            //Insert into expense
            DatabaseQuery.ExecStringProcNoReturn(StoredProcs.InsertExpense(_cat,_amount,_date,_desc, _acct, _company, _location));
        }
        public void InsertIncome(string _date, string _cat, string _amount, string _desc, string _acct, string _company, string _location)
        {
            //insert into income
            DatabaseQuery.ExecStringProcNoReturn(StoredProcs.InsertIncome(_cat, _amount, _date, _desc, _acct));
        }

        public void GetFromFile()
        {
            //some temp stuff to parse a csv into the db
            StreamReader sr = new StreamReader(@"C:\Users\Pete\Desktop\parse.txt");
            while (true)
            {
                string s = sr.ReadLine();
                string cat = "30";
                if (s == null )
                {
                    sr.Close();
                    break;
                }
                
                string[] parsed = s.Split('~');
                if(parsed.Length < 4)
                {
                    continue;
                }
                if(parsed[3].Contains("AIRWAY"))
                {
                    cat = "19";
                }
                else if (parsed[3].Contains("SHELL"))
                {
                    cat = "17";
                }
                else if (parsed[3].Contains("AMOCO"))
                {
                    cat = "17";
                }
                else if (parsed[3].Contains("PIZZA"))
                {
                    cat = "12";
                }
                else if (parsed[3].Contains("CHOPPER"))
                {
                    cat = "23";
                }
                else if (parsed[3].Contains("MASSPORT"))
                {
                    cat = "19";
                }


                string[] date = parsed[1].Split('/');
                //InsertExpense(date[0] + "/" + date[1] + "/" + "2010",
                //    cat,
                //    parsed[parsed.Length - 1],
                //    parsed[3],
                //    "");
            }

        }

        private void rbIncome_CheckedChanged(object sender, EventArgs e)
        {
            //repopulated the category drop down because income and expense are different
            ReloadCategoryDDL();
        }

        private void rbExpense_CheckedChanged(object sender, EventArgs e)
        {
            //repopulated the category drop down because income and expense are different
            ReloadCategoryDDL();
        }
        private void ReloadCategoryDDL()
        {
            if (rbExpense.Checked)
            {
                dbData.PopulateDDLFromDictionary(dbData.GetExpenseCategoryDict(), ddlCategory);
            }
            else
            {
                dbData.PopulateDDLFromDictionary(dbData.GetIncomeCategoryDict(), ddlCategory);
            }
            if(ddlCategory.Items.Count > 0)
            {
                ddlCategory.SelectedIndex = 0;
            }
            ddlFrequency.SelectedItem = "One Time";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GetFromFile();
        }

        private void txtAmount_Leave(object sender, EventArgs e)
        {
            try
            {
                txtAmount.Text=txtAmount.Text.Replace("$", "");
                txtAmount.Text = txtAmount.Text.Replace(",", "");
                decimal t = decimal.Parse(txtAmount.Text);
                txtAmount.Text = t.ToString("C");
            }
            catch
            {
                txtAmount.Text = "$0.00";
            }
        }

        private void txtDesc_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.DefaultLocation = txtLocation.Text;
        }
    }
}
